<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-form-model-item label="区域" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="areaId">
          <j-select-depart placeholder="请选择区域id" v-model="model.areaId" />
        </a-form-model-item>
        <a-form-model-item
          v-show="model.areaId"
          label="管点编号"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          prop="pointNo"
        >
          <a-select
            v-model="model.pipPointNo"
            show-search
            placeholder="请输入管点编号"
            :default-active-first-option="false"
            :show-arrow="false"
            :filter-option="false"
            :not-found-content="null"
            :options="pointDatalist"
            @search="querySearchPipPointAsync"
            @change="handleSelectPipPoint"
          >
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="设施类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="facilityType">
          <j-dict-select-tag
            type="list"
            v-model="model.facilityType"
            dictCode="sewage_ps_point_type"
            placeholder="请选择设施类型"
          />
        </a-form-model-item>
        <div v-show="model.facilityType === '1'">
          <a-form-model-item label="污水处理厂名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="facilityName">
            <a-input v-model="model.facilityName" placeholder="请输入污水处理厂名称" style="width: 100%" />
          </a-form-model-item>
          <a-form-model-item label="污水处理厂基面" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="facilityArea">
            <a-input v-model="model.facilityArea" placeholder="请输入污水处理厂基面"></a-input>
          </a-form-model-item>
          <a-form-model-item label="日均污水处理量" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="dailyAvg">
            <a-input v-model="model.dailyAvg" placeholder="请输入日均污水处理量" style="width: 100%" />
          </a-form-model-item>
          <a-form-model-item label="处理村庄" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="handleTowns">
            <a-select
              v-model="model.handleTownsArr"
              mode="multiple"
              show-search
              allowClear
              :default-value="[]"
              placeholder="请选择村庄"
              option-filter-prop="children"
            >
              <a-select-option v-for="item in townsList" :key="item.value" :value="item.value">
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </div>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'
import { validateDuplicateValue, simpleDebounce } from '@/utils/util'

export default {
  name: 'FacilityForm',
  components: {},
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    return {
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      validatorRules: {},
      url: {
        add: '/paishui/paishuiFacility/add',
        edit: '/paishui/paishuiFacility/edit',
        queryById: '/paishui/paishuiFacility/queryById'
      },
      pointDatalist: [], //检索管点列表
      townsList: [] //村庄列表
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    }
  },
  watch: {
    'model.facilityType'(facilityType) {
      if (facilityType !== '1') {
        this.model.facilityName = ''
        this.model.facilityArea = ''
        this.model.dailyAvg = ''
        this.model.handleTowns = ''
      }
    }
  },
  created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
    this.getTowmList()
    this.querySearchPipPointAsync = simpleDebounce(this.querySearchPipPointAsync, 500)
    this.filterTownsList = simpleDebounce(this.filterTownsList, 500)
  },
  methods: {
    async getTowmList() {
      // pageNo	pageSize townName
      const res = await getAction(`sys/sysDepart/list/${6}`, { pageNo: 1, pageSize: 10000 })
      const townsList = res.result || []
      this.townsList = townsList.map(town => ({
        value: town.id,
        label: town.departName
      }))
    },
    // 管点-远程模糊搜索
    async querySearchPipPointAsync(pointNo) {
      if (!pointNo) {
        return
      }
      const areaId = this.model.areaId
      const res = await getAction(`/paishui/pipPoint/list?areaId=${areaId}&pipNo=*${pointNo}*`)
      const pointDatalist = res.result.records || []
      this.pointDatalist = pointDatalist.map(item => ({
        value: item.pipNo,
        label: item.pipName,
        longitude: item.longitude,
        latitude: item.latitude
      }))
    },
    handleSelectPipPoint(pointNo) {
      // console.log('handleSelectPipPoint', pointNo)
      const pointItem = this.pointDatalist.find(item => item.value === pointNo)
      this.model.longitude = pointItem.longitude
      this.model.latitude = pointItem.latitude
    },
    add() {
      this.edit(this.modelDefault)
    },
    edit(record) {
      this.model = Object.assign({}, { ...record, handleTownsArr: [] })
      this.model.facilityType && (this.model.facilityType += '')
      if (this.model.handleTowns) {
        this.model.handleTownsArr = JSON.parse(this.model.handleTowns).map(item => item.value)
      } else {
        this.model.handleTownsArr = []
      }
      this.visible = true
    },
    submitForm() {
      const that = this
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          let handleTowns = []
          let handleTownsStr = ''
          if (this.model.handleTownsArr.length) {
            this.townsList.map(item => {
              if (this.model.handleTownsArr.includes(item.value)) {
                handleTowns.push(item)
              }
            })
            handleTownsStr = JSON.stringify(handleTowns)
          }
          httpAction(httpurl, { ...this.model, handleTowns: handleTownsStr, handleTownsArr: null }, method)
            .then(res => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    }
  }
}
</script>
